package com.cos.shop.dao.impl;

import com.cos.shop.dao.OrderDao;
import com.cos.shop.entity.Address;
import com.cos.shop.entity.Orders;
import com.cos.shop.util.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: COS
 * @time: 2022/2/25 10:25
 * @description:
 */
public class OrderDaoImpl implements OrderDao {

    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public int chageOrderStateByOid(String oid, int isPay) throws SQLException {
        return qr.update("update orders set ostate = ? where oid= ?",
                isPay,oid);
    }

    @Override
    public Orders getOrderWithAdressByOid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {
        Map<String, Object> query = qr.query("select " +
                "o.oid,o.uid,o.aid,o.ocount,o.otime,o.ostate,a.aname,a.aphone,a.adetail " +
                "from orders o,address a where o.aid=a.aid and o.oid = ?", new MapHandler(), oid);

        if (query!=null) {
            //创建需要封装数据的对象
            Orders o = new Orders();
            Address a = new Address();
            //工具类
            BeanUtils.populate(o,query);
            BeanUtils.populate(a,query);
            //手动封装对象数据
            o.setAddress(a);
            return o;
        }
        return null;
    }

    @Override
    public List<Orders> getOrderListByUid(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<Map<String, Object>> query = qr.query("select " +
                        "o.oid,o.uid,o.aid,o.ocount,o.otime,o.ostate,a.aname,a.aphone,a.adetail " +
                        "from orders o,address a where o.aid=a.aid and o.uid= ?",
                new MapListHandler(), uid);
        if (query != null && query.size() > 0) {
            List<Orders> ordersList = new ArrayList<>();
            for (Map<String, Object> map : query) {
                //创建需要封装数据的对象
                Orders o = new Orders();
                Address address = new Address();
                //工具类
                BeanUtils.populate(o, map);
                BeanUtils.populate(address, map);
                //手动封装对象
                o.setAddress(address);
                ordersList.add(o);
            }
            return ordersList;
        }
        return null;
    }


    @Override
    public int addOrder(Orders orders) throws SQLException {
        return qr.update("insert into orders values (?,?,?,?,?,?)",
                orders.getOid(), orders.getUid(), orders.getAid(),
                orders.getOcount(), orders.getOtime(), orders.getOstate());
    }
}
